<?php


namespace app\admin\controller\reau;

use app\api\controller\Order;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;
use think\facade\Env;

/**
 * @ControllerAnnotation(title="退款审核列表")
 */
class RefundAudit extends AdminController
{

    use \app\admin\traits\Curd;
    protected $sort = [
        'id'   => 'desc',
    ];
    protected $wechat_config = [];

    public function __construct(App $app)
    {
        $this->wechat_config = [
            // 'token'          => 'test',
            'appid' => Env::get('pay.appid'),
            'appsecret' => '',
            'encodingaeskey' => '',
            // 配置商户支付参数（可选，在使用支付功能时需要）
            'mch_id' => Env::get('pay.mchid'),
            'mch_key' => Env::get('pay.apikey'),
            // 配置商户支付双向证书目录（可选，在使用退款|打款|红包时需要）
            'ssl_key' => root_path() . '/cert/apiclient_key.pem',
            'ssl_cer' => root_path() . '/cert/apiclient_cert.pem',
            // 缓存目录配置（可选，需拥有读写权限）
            'cache_path' => '',
        ];
        parent::__construct($app);
        $this->model = new \app\admin\model\Order();
        
    }
    
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->where("status",2)
                ->where("is_order_refund",1)
                ->count();
            $list = $this->model
                ->where($where)
                ->where("status",2)
                ->where("is_order_refund",1)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            foreach ($list as $k => $v){
                //service_gid
                $service_goods = Db::name("service_goods")->where("id",$v["service_gid"])->find();
                $v['service_name'] = $service_goods['title'];
                $v['service_img'] = $service_goods['zhu_img'];
                $list[$k] = $v;
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
     

    /**
    * @NodeAnotation(title="通过")
    */
    public function adopt_url()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $ret = $this->model->where('id', $post['id'])->where('status', 2)->where('is_order_refund', 1)->find();
            if (empty($ret)) {
                $this->error('当前订单不能退款');
            }
            $ret = $ret->toArray();
            $result = $this->twxchat_back($ret['transaction_id'], $ret['order_no'], $ret['payable_money'] * 100);
            if($result['code'] == 1){
                $this->model->where('id', $post['id'])->update(['status' => 5,'is_order_refund' =>2]);
                Db::name("service_duration")->where("id",$ret['spec_id'])->inc("stock")->update();
                $this->success('退款成功', '');
            } else {
                $this->model->where('id', $post['id'])->update(['fail_msg' => $result['msg']]);
                $this->error('退款失败');
            }
        }
        return $this->fetch();
    }

    public function twxchat_back($transaction_id, $out_refund_no, $money)
    {
        try {
            $wechat = \WeChat\Pay::instance($this->wechat_config);
             $options = [
                'transaction_id' => $transaction_id,
                'out_refund_no'  => $out_refund_no,
                'total_fee'      => $money,
                'refund_fee'     => $money,
            ];
            $result = $wechat->createRefund($options);
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                return ['code' =>1, 'data' => $result];
            } else{
                return ['code'=>0, 'msg'=>$result['err_code_des']];
            }
        } catch (\Throwable $th) {
            return ['code'=>0, 'msg'=>$th->getMessage()];
        }
    }

      /**
    * @NodeAnotation(title="驳回")
    */
    public function reject_url()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post["reason_for_rejection"])){
                $this->error("驳回原因不能为空");
            }
           
            Db::name("order")->where("id",$post["id"])->update(["status"=>6,"is_order_refund"=>3,"reason_for_rejection"=>$post["reason_for_rejection"]]);
            $this->success('驳回成功', '');
        }
        return $this->fetch();
    }

    
 
} 